// 看看在析构的时候能不能调用public接口
// 结论：可以，所以不能并发析构，推荐使用RefBase

#include <stdio.h>
#include <thread>
#include <unistd.h>
#include <mutex>

class Object {
public:
    Object(void *ptr)
    {
        p = ptr;
    }

    ~Object()
    {
        destroying = true;
        sleep(0); // 概率增大器, 进程调度
        p = nullptr;
    }

    void Func()
    {
        static int i = 0;
        static int j = 0;
        i++;
        if (destroying && p != nullptr) {
            printf("\r%d/%d !", i, j++);
            return;
        }
        printf("\r%d/%d !", i, j);
    }

private:
    void *p = nullptr;
    bool destroying = false;
};

int main()
{
    Object *o = nullptr;
    std::thread thread([&]() {
        for (int i = 0; i < 1e7; i++) {
            if (o != nullptr) {
                o->Func();
            }
        }
    });

    for (int i = 0; i < 1e7; i++) {
        o = new Object(&o);
        delete o;
    }
    thread.join();
    return 0;
}
